package com.yc.c118s3plyqnzf.controller;

import com.yc.c118s3plyqnzf.entity.Users;
import com.yc.c118s3plyqnzf.service.BizException;
import com.yc.c118s3plyqnzf.service.IUsersService;
import com.yc.c118s3plyqnzf.vo.Result;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lcx
 * @since 2022-11-28
 */
@RestController
@RequestMapping("/c118s3plyqnzf/users")
public class UsersController {

    @Resource
    IUsersService usersService;

    @PostMapping("login")
    public Result login(@RequestBody @Valid Users users, Errors errors, HttpSession session) throws BizException {
        if (errors.hasFieldErrors("username")
                || errors.hasFieldErrors("password")){
            throw  new BizException("输入错误", errors.getAllErrors());
        }

        try {
            Users login = usersService.login(users);
            session.setAttribute("loginedUser", login);
        } catch (BizException e) {
            errors.reject("login.error", e.getMessage());
            throw  new BizException(e.getMessage(), errors.getAllErrors());
        }
        return new Result(1, "登录成功", null);

    }

    @RequestMapping("logout")
    Result logout(HttpSession session){
        session.invalidate();
        return new Result(1, "退出成功", null);
    }

    @RequestMapping("getLoginedUser")
    Result getLoginedUser(@SessionAttribute(required = false) Users loginedUser){
        // session.getAttribute("loginedUser");
        if (loginedUser == null){
            return new Result(0, "未登录", null);
        } else {
            return new Result(1, "已登录", loginedUser);
        }
    }

}
